import 'package:fluent_ui/fluent_ui.dart';

import '../../api/school_class_timetable_api.dart';
import '../../components/data_table.dart';
import '../../model/school_class_timetable_model.dart';
import '../../utils/loading_utils.dart';
import '../app/app_dict_data.dart';

abstract class ClassTimetableDetailField {}

///学校班级课表详情:查询字段
enum ClassTimetableDetailQueryField implements ClassTimetableDetailField {
  week('星期'),
  segment('节次'),
  subject('科目'),
  teacher('教师'),
  status('状态');

  final String label;

  const ClassTimetableDetailQueryField(this.label);
}

///学校班级课表详情:输入字段
enum ClassTimetableDetailInputField implements ClassTimetableDetailField {
  remark('备注'),
  week('星期', checked: true),
  segment('节次', checked: true),
  subject('科目', checked: true),
  teacher('教师'),
  teacherAbbr('教师简称'),
  status('状态', isAdd: false);

  final String label;
  final bool checked, isAdd;

  const ClassTimetableDetailInputField(
    this.label, {
    this.checked = false,
    this.isAdd = true,
  });

  String? validHandler<T>(final T? val) {
    if (checked) {
      if (val == null) {
        return '$label不能为空';
      }
      if (val is String) {
        return val.isEmpty ? '$label不能为空' : null;
      }
      if (val is List) {
        return val.isEmpty ? '$label不能为空' : null;
      }
    }
    return null;
  }
}

///学校班级课表详情:视图模型
class SchoolClassTimetableDetailViewModel extends ChangeNotifier {
  //查询字段
  final _queryFields = <ClassTimetableDetailQueryField, TextEditingController>{
    for (var field in ClassTimetableDetailQueryField.values)
      field: TextEditingController()
  };

  //输入字段
  final _inputFields = <ClassTimetableDetailInputField, TextEditingController>{
    for (var field in ClassTimetableDetailInputField.values)
      field: TextEditingController()
  };

  ///获取控制器
  TextEditingController? getController<T extends ClassTimetableDetailField>(
      final T field) {
    //查询字段
    if (field is ClassTimetableDetailQueryField) {
      return _queryFields[field];
    }
    //输入字段
    if (field is ClassTimetableDetailInputField) {
      return _inputFields[field];
    }
    return null;
  }

  ///获取字段值
  String? getFieldValue<T extends ClassTimetableDetailField>(final T field) {
    final ctr = getController(field);
    if (ctr != null) {
      return ctr.text;
    }
    return null;
  }

  ///设置字段值
  void setFieldValue<T extends ClassTimetableDetailField>(
      T field, String? val) {
    final controller = getController(field);
    if (controller != null) {
      controller.text = val ?? '';
    }
  }

  final _statusOpts = <ComboBoxItem<String>>[];

  ///获取状态选项集合
  List<ComboBoxItem<String>> get statusOpts => _statusOpts;

  ///加载字典处理
  void _loadDict(final List<Future<dynamic>> futures) {
    //状态
    if (_statusOpts.isEmpty) {
      final future = appDictData.buildOpts('status').then((opts) {
        if (opts.isNotEmpty) {
          _statusOpts.addAll(opts);
        }
      });
      futures.add(future);
    }
  }

  ///加载初始化
  void loadInit({final VoidCallback? afterHandler}) async {
    final futures = <Future<dynamic>>[];
    //加载字典
    _loadDict(futures);
    //请求等待
    if (futures.isNotEmpty) {
      await Future.wait(futures);
      //触发
      notifyListeners();
    }
    //回调处理
    if (afterHandler != null) {
      afterHandler.call();
    }
  }

  //清空查询字段
  void cleanQueryFields() {
    for (var controller in _queryFields.values) {
      controller.clear();
    }
  }

  ///清空输入字端
  void cleanInputFields() {
    for (var controller in _inputFields.values) {
      controller.clear();
    }
  }

  ///分页查询模型
  final queryModel = PageModel<SchoolClassTimetableDetailItemRes>();

  ///分页查询
  void query(final String classTimetableId) async {
    try {
      loading.showLoading();
      final weekVal = getFieldValue(ClassTimetableDetailQueryField.week);
      final segment = getFieldValue(ClassTimetableDetailQueryField.segment);
      final subjectVal = getFieldValue(ClassTimetableDetailQueryField.subject);
      final status = getFieldValue(ClassTimetableDetailQueryField.status);
      final req = SchoolClassTimetableDetailQueryReq(
        classTimetableId: classTimetableId,
        weekVal: int.tryParse(weekVal ?? '') ?? -1,
        segment: int.tryParse(segment ?? '') ?? -1,
        subjectVal: int.tryParse(subjectVal ?? '') ?? -1,
        teacherId: getFieldValue(ClassTimetableDetailQueryField.teacher) ?? '',
        status: int.tryParse(status ?? '') ?? -1,
      );
      final res = await schoolClassTimetableApi.queryDetail(req);
      if (res.isSuccessed) {
        queryModel.buildResData(res);
      }
      debugPrint(
        'schoolClassTimetableApi.queryDetail(req:${req.toMap()})=>$res',
      );
    } finally {
      loading.dismiss();
    }
  }

  ///加载数据
  void getInfoById(final String id) async {
    try {
      loading.showLoading();
      //加载数据
      final res = await schoolClassTimetableApi.infoDetail(id);
      if (res.isSuccessed) {
        setFieldValue(ClassTimetableDetailInputField.remark, res.remark);
        setFieldValue(ClassTimetableDetailInputField.week, '${res.weekVal}');
        setFieldValue(
          ClassTimetableDetailInputField.segment,
          '${res.segment}',
        );
        setFieldValue(
          ClassTimetableDetailInputField.subject,
          '${res.subjectVal}',
        );
        setFieldValue(ClassTimetableDetailInputField.teacher, res.teacherId);
        setFieldValue(ClassTimetableDetailInputField.status, '${res.status}');
        //触发通知
        notifyListeners();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///新增处理
  void onAddHandler(String classTimetableId, VoidCallback handler) async {
    try {
      loading.showLoading();
      //新增处理
      final weekVal = getFieldValue(ClassTimetableDetailInputField.week);
      final segment = getFieldValue(ClassTimetableDetailInputField.segment);
      final subjectVal = getFieldValue(ClassTimetableDetailInputField.subject);
      final req = SchoolClassTimetableDetailAddReq(
        classTimetableId: classTimetableId,
        remark: getFieldValue(ClassTimetableDetailInputField.remark) ?? '',
        weekVal: int.tryParse(weekVal ?? '') ?? 0,
        segment: int.tryParse(segment ?? '') ?? 0,
        subjectVal: int.tryParse(subjectVal ?? '') ?? 0,
        teacherId: getFieldValue(ClassTimetableDetailInputField.teacher) ?? '',
        teacherAbbr:
            getFieldValue(ClassTimetableDetailInputField.teacherAbbr) ?? '',
      );
      //新增
      final res = await schoolClassTimetableApi.addDetail(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///修改处理
  void onModifyHandler(final String id, final VoidCallback handler) async {
    try {
      loading.showLoading();
      final weekVal = getFieldValue(ClassTimetableDetailInputField.week);
      final segment = getFieldValue(ClassTimetableDetailInputField.segment);
      final subjectVal = getFieldValue(ClassTimetableDetailInputField.subject);
      final status = getFieldValue(ClassTimetableDetailInputField.status);
      //修改处理
      final req = SchoolClassTimetableDetailModifyReq(
        id: id,
        remark: getFieldValue(ClassTimetableDetailInputField.remark) ?? '',
        weekVal: int.tryParse(weekVal ?? '') ?? 0,
        segment: int.tryParse(segment ?? '') ?? 0,
        subjectVal: int.tryParse(subjectVal ?? '') ?? 0,
        teacherId: getFieldValue(ClassTimetableDetailInputField.teacher) ?? '',
        teacherAbbr:
            getFieldValue(ClassTimetableDetailInputField.teacherAbbr) ?? '',
        status: int.tryParse(status ?? '') ?? 1,
      );
      //修改
      final res = await schoolClassTimetableApi.modifyDetail(req);
      if (res.isSuccessed) {
        cleanInputFields();
        handler.call();
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }

  ///删除处理
  void onDeleteHandler({required final String classTimetableId, id}) async {
    try {
      loading.showLoading();
      //删除
      final res = await schoolClassTimetableApi.deleteDetail(id);
      if (res.isSuccessed) {
        query(classTimetableId);
        return;
      }
      final String err;
      if ((err = res.retMessage).isNotEmpty) {
        loading.showToast(err);
      }
    } finally {
      loading.dismiss();
    }
  }
}
